import React, { Component } from 'react'
// 引入store，用户获取redux状态
import store from '../../redux/store'
// 引入action creator，专门用户创建action对象
import { createIncrementAction, createDecrementAction, createIncrementAsyncAction } from '../../redux/count_action'

export default class Count extends Component {
  state = {
    count: 0
  }

  // componentDidMount() {
  //   // 检测redux中状态的变化，只要变化了就调用
  //   store.subscribe(() => {
  //     this.setState({})
  //   })
  // }

  increment = () => {
    const { value } = this.selectedNum
    store.dispatch(createIncrementAction(Number(value)))
  }

  decrement = () => {
    const { value } = this.selectedNum
    store.dispatch(createDecrementAction(Number(value)))
  }

  // 奇数再加
  incrementWhenOdd = () => {
    const { value } = this.selectedNum
    const count = store.getState()
    if (count % 2 !== 0) {
      store.dispatch(createIncrementAction(Number(value)))
    }
  }

  incrementAsync = () => {
    const { value } = this.selectedNum
    store.dispatch(createIncrementAsyncAction(Number(value), 500))
  }

  render() {
    return (
      <div className="container">
        <h1>当前求和为：{store.getState()}</h1>

        <div className="row">
          <div className="col-auto">
            <select className="form-select" ref={e => (this.selectedNum = e)}>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
            </select>
          </div>
          <div className="col">
            <button className="btn btn-primary me-2" onClick={this.increment}>
              +
            </button>
            <button className="btn btn-primary me-2" onClick={this.decrement}>
              -
            </button>
            <button className="btn btn-primary me-2" onClick={this.incrementWhenOdd}>
              当前求和为奇数再加
            </button>
            <button className="btn btn-primary" onClick={this.incrementAsync}>
              异步加
            </button>
          </div>
        </div>
      </div>
    )
  }
}
